package com.syt.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.syt.oss.service.OssService;
import com.syt.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    //上传文件到OSS
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        String endpoint= ConstantPropertiesUtils.END_POINT;
        String accessKeyId=ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret=ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName=ConstantPropertiesUtils.BUCKET_NAME;

        try {
            //创建OSS实例
            OSS oss=new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String filename = file.getOriginalFilename();
            filename=uuid+filename;
            //文件按照日期分类
            //获取当前日期
            String dataPath = new DateTime().toString("yyyy/MM/dd");
            filename=dataPath+"/"+filename;
            oss.putObject(bucketName, filename,inputStream);
            //关闭OSSClient
            oss.shutdown();
            //把上传文件路径返回
            //需要把自己上传到OSS路径手动拼接出来
            return "https://"+bucketName+"."+endpoint+"/"+filename;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
